﻿using System;
using System.Web;
using System.Text;
using System.Web.UI;

/// <summary>
/// A JavaScript alert
/// </summary>
public static class Alert
{
    /// <summary>
    /// Shows a client-side JavaScript alert in the browser.
    /// </summary>
    /// <param name="message">The message to appear in the alert.</param>
    public static void ShowMessage(string message)
    {
        // Cleans the message to allow single quotation marks
        string cleanMessage = message.Replace("'", "\\'");
        string script = "<script type=\"text/javascript\">alert('" + cleanMessage + "');</script>";

        // Gets the executing web page
        Page page = HttpContext.Current.CurrentHandler as Page;

        // Checks if the handler is a Page and that the script isn't allready on the Page
        if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert"))
        {
            page.ClientScript.RegisterClientScriptBlock(typeof(Alert), "alert", script);
        }
    }

    public static void OkConfirm(string message, string hyperLink)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.Append(@"script language=JavaScript>");
        sb.Append(@"if (confirm('" + message + "')) {location='" + hyperLink + "'};");
        sb.Append(@"</");
        sb.Append(@"script>");

        ((System.Web.UI.Page)HttpContext.Current.Handler).RegisterStartupScript(new Guid().ToString(), sb.ToString());
    }

    /// Displays a prompt box that will direct the user to a specified hyperlink with a specified querystring definition for an ok click or a cancel click. The querystring value will be inserted by the entered value in the prompt box only if ok was clicked. No need to enter any equal or question mark characters.
    public static void PromptBox(string message, string defaultPromptvalue, string hyperlink, string queryString, string cancelHyperlink)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.Append(@"-script language=JavaScript>");
        sb.Append(@"var return_value = prompt('" + message + "', '" + defaultPromptvalue + "');");
        sb.Append(@"if (return_value != null)");
        sb.Append(@"{location='" + hyperlink + "?" + queryString + "=' + return_value;}");
        sb.Append(@"else");
        sb.Append(@"{location='" + cancelHyperlink + ";}");
        sb.Append(@"");
        sb.Append(@"</");
        sb.Append(@"script>");

        ((System.Web.UI.Page)HttpContext.Current.Handler).RegisterStartupScript(new Guid().ToString(), sb.ToString());
    } 
}
